利用Java中使用Set進行並集,差集,交集查找
首先命名一個類名爲DealSet存放查找並集,差集,交集的方法
DealSet.java
package SetLearning;
import java.util.HashSet;
import java.util.Set;
public class DealSet<T> {
private Set<T> differentSet ;
private Set<T> sameSet ;
private Set<T> unionSet ;
/*
* union方法計算並集
*/
public Set<T> Union(Set<T> s1 , Set<T> s2){
unionSet = new HashSet<T>();
/*
* 利用Set的元素不可重複特性往unionSet中添加元素形成並集
*/
for(T s : s1){
unionSet.add(s);
}
for(T s : s2){
unionSet.add(s);
}
return unionSet ;
}
/*
* sameSet方法返回並集
*/
public Set<T> sameSet(Set<T> s1 , Set<T> s2){
sameSet = new HashSet<T>();
/*
* 利用ForEach循環和HashSet中的contains方法判斷兩個Set中元素是否相交
* 相交則存入SameSet中
*/
for(T s : s1){
if(s2.contains(s))
sameSet.add(s);
}
return sameSet;
}
/*
* differentSet方法返回差集
*/
public Set<T> differentSet(Set<T> s1 , Set<T> s2){
differentSet = new HashSet<T>();
/*
* 利用ForEach循環和HashSet中的contains方法判斷兩個Set中元素是否相交
* 不相交則存入differentSet中
*/
for(T s : s1){
if(!s2.contains(s))
differentSet.add(s);
}
return differentSet;
}
}
代碼中,由於differentSet與sameSet算法可以合併,可以提高效率。
但由於某些情況下並不需要差集與交集同時計算,所以分開之。
接下來寫測試類
DealSetTest.java
package SetLearning;
import java.util.HashSet;
import java.util.Set;
public class DealSetTest {
public static void main(String[] args) {
/*
* 初始化兩個HashSet
*/
Set<String> hashSet1 = new HashSet<>();
Set<String> hashSet2 = new HashSet<>();
/*
* 創建連個字符串數組,用於儲存兩個HashSet中元素
*/
String[] s1 = {"George" , "Jim" , "John" , "Blake" , "Kevin" , "Mechael"};
String[] s2 = {"George" , "Katie" , "Ryan" , "Kevin" , "Mechael"};
/*
* 使用ForEach循環向Hash中添加元素
* 避免一行一行添加造成代碼不美觀
*/
for(String s : s1){
hashSet1.add(s);
}
for(String s : s2){
hashSet2.add(s);
}
/*
* 調用DealSet累中個方法進行計算
*/
DealSet<String> ds = new DealSet<String>();
System.out.println("Union Set is "+ds.Union(hashSet1, hashSet2));
System.out.println("Different Set is " + ds.differentSet(hashSet1, hashSet2));
System.out.println("Same Set is " + ds.sameSet(hashSet1, hashSet2));
}
}